package gameSite;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet 
{
	private static final long serialVersionUID = 1L;
    public LoginServlet(){  super(); }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}

    
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		
		String user = request.getParameter("user");
		String pass = request.getParameter("pass");
		System.out.println("User and Pass  " + user + "  " + pass);
		JDBCdriver connector = new JDBCdriver();
		Connection connection = connector.getConnectionToDatabase();
		ResultSet resultSet = null;
		
		try 
		  {
			Statement queryConnection = connection.createStatement();
			String querySQL = "SELECT userName, password FROM Users WHERE userName = \""+user+"\" AND password = \""+pass+"\";"; 
			//String querySQL = "SELECT * FROM login;";
			System.out.println("start Query");
			 resultSet = queryConnection.executeQuery(querySQL);
			
			System.out.println("ended Query");

			if(resultSet.isBeforeFirst())
			{

					resultSet.first();

				if(resultSet.getString("userName").equals(user))
				{
					System.out.println("         --------------username: true ------------        "+resultSet.getString("username"));
				
					if(resultSet.getString("password").equals(pass))
					{
						System.out.println("         --------------password: true ------------        "+resultSet.getString("password"));
				
						//logged-In So Create Session
						SessionHandler session = new SessionHandler(request, response);
						request.getSession().setAttribute("session", session);
						request.getSession().setAttribute("userName", user);
						response.sendRedirect("homeJSPLoggedIn.jsp");
						return;
					
					}
					else
					{
						System.out.println("         --------------password: false ------------        "+resultSet.getString("password"));
					}
				}
				else
				{
					System.out.println("         --------------username: false ------------        "+resultSet.getString("username"));
				}
			}
			else
			{
				System.out.println("cursor was not before first");
			}
			
//			response.sendRedirect("homeJSP.jsp");

		  }
		  catch (SQLException e) 
		  {
			  e.printStackTrace();
		  }
		  
	}

}
